from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, logout, authenticate
from .models import Book, Author
from django.http import HttpResponse


# 主页 + 会话访问计数器
def home(request):
    # 从会话中获取计数，无则初始化为 0
    count = request.session.get('visit_count', 0)
    request.session['visit_count'] = count + 1  # 每次访问 +1
    return render(request, 'home.html', {'count': count})


# 登录
def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            login(request, user)
            return redirect('home')  # 登录后返回主页
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    return render(request, 'login.html')


# 登出
@login_required
def user_logout(request):
    logout(request)
    return redirect('home')


# 查看已借图书（需登录）
@login_required
def borrowed_books(request):
    books = Book.objects.filter(borrower=request.user)
    return render(request, 'borrowed_books.html', {'books': books})


# 图书借还、创建、更新、删除（核心功能）
@login_required
def book_manage(request, book_id=None):
    if book_id:
        book = get_object_or_404(Book, pk=book_id)
    else:
        book = None

    if request.method == 'POST':
        if 'borrow' in request.POST:  # 借阅
            book.borrower = request.user
            book.save()
        elif 'return' in request.POST:  # 归还
            book.borrower = None
            book.save()
        else:  # 创建/更新
            title = request.POST['title']
            author_id = request.POST['author']
            author = get_object_or_404(Author, pk=author_id)

            if book:  # 更新
                book.title = title
                book.author = author
                book.save()
            else:  # 创建
                Book.objects.create(title=title, author=author)
            return redirect('book_manage')  # 操作后返回管理页

    authors = Author.objects.all()
    books = Book.objects.all()
    return render(request, 'book_manage.html', {
        'books': books,
        'authors': authors,
        'current_book': book
    })


# 作者列表
def author_list(request):
    authors = Author.objects.all()
    return render(request, 'author_list.html', {'authors': authors})


# 作者详情
def author_detail(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    return render(request, 'author_detail.html', {'author': author})